﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using PowerGui.AddOn.Interfaces;

namespace PowerGUIVsx
{
    internal class VisualStudioCommandKeyMappings : ICommandKeyMappings
    { 
        public Keys ToggleBreakpoint
        {
            get
            {
                return GetKeys("Debug.ToggleBreakpoint");
            }
        }

        private static Keys GetKeys(string name)
        {
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE2;

            if (dte != null)
            {
                try
                {
                    foreach (Command command in dte.Commands)
                    {
                        if (command.Name == name)
                        {
                            var bindings = command.Bindings as object[];

                            if (bindings != null && bindings.Length > 0)
                            {
                                var stringBindings = GetBindings(bindings);

                                Keys value = Keys.None;
                                foreach(var s in stringBindings)
                                {
                                    Keys currentValue;
                                    if (Enum.TryParse(s, true, out currentValue))
                                    {
                                        value |= currentValue;    
                                    }
                                }

                                return value;
                            }
                        }

                    }
                }
                catch (InvalidComObjectException)
                {
                    // user closed the window or closed Visual Studio.
                }
            }

            return Keys.None;
        }

        private static List<string> GetBindings(IEnumerable<object> bindings)
        {
            var result = bindings.Select(binding => binding.ToString().IndexOf("::") >= 0
                ? binding.ToString().Substring(binding.ToString().IndexOf("::") + 2)
                : binding.ToString()).ToList();

            return result;
        }

    }
}
